package org.dxy.domain.handler.workorder;

import com.google.common.eventbus.EventBus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.port.IEventRepository;
import org.dxy.domain.handler.CommandHandler;
import org.dxy.domain.port.repository.IWorkOrderRepository;
import org.dxy.domain.command.workorder.CompleteWorkOrderCommand;
import org.dxy.domain.event.DomainEvent;
import org.dxy.domain.model.aggregate.WorkOrder;
import org.dxy.types.common.CommandResult;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.List;

/**
 * 完成工单命令处理器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CompleteWorkOrderCommandHandler implements CommandHandler<CompleteWorkOrderCommand, Void> {

    private final IWorkOrderRepository workOrderRepository;
    private final EventBus eventBus;
    private final IEventRepository eventRepository;
    
    @Transactional
    @Override
    public CommandResult<Void> handle(CompleteWorkOrderCommand command) {
        // 1. 查找工单
        WorkOrder workOrder = workOrderRepository.findById(command.workOrderId());
        if (workOrder == null) {
            throw new IllegalArgumentException("工单不存在");
        }
        
        // 2. 执行业务操作
        workOrder.complete(command);
        
        // 3. 保存聚合根
        workOrderRepository.save(workOrder);

        List<DomainEvent> events = workOrder.getDomainEvents();
        // 4. 保存事件到事件存储
        eventRepository.saveEvents(events);
        
        // 5. 注册事务提交后的事件发布回调
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCommit() {
                events.forEach(eventBus::post);
            }
        });

        List<Long> eventIds = events.stream().map(DomainEvent::eventId).toList();

        // 当事件发布成功后，会把这个字段标记为 true；
        //如果系统崩溃或重启，可以扫描未发布的事件（published = false）重新发布，保证"最终一致性"。
        eventRepository.markEventsPublished(eventIds);
        
        // 6. 清理事件
        workOrder.clearDomainEvents();
        
        log.info("工单完成成功, command={}", command);
        return CommandResult.success(null, "工单完成成功");
    }
}